﻿using System;
using System.Globalization;
using System.IO;
using System.Resources;

namespace Microsoft.Xna.Framework.Content
{
	/// <summary>
	/// Subclass of ContentManager, which is specialized to read from .resx resource files rather than directly from individual files on disk.
	/// </summary>
	public class ResourceContentManager : ContentManager
	{
		private ResourceManager resourceManager;

		/// <summary>
		/// Creates a new instance of ResourceContentManager.
		/// </summary>
		/// <param name="serviceProvider">The service provider the ContentManager should use to locate services.</param>
		/// <param name="resourceManager">The resource manager for the ResourceContentManager to read from.</param>
		public ResourceContentManager(IServiceProvider serviceProvider, ResourceManager resourceManager)
			: base(serviceProvider)
		{
			if (resourceManager == null)
			{
				throw new ArgumentNullException("resourceManager");
			}
			this.resourceManager = resourceManager;
		}

		/// <summary>
		/// Opens a stream for reading the specified resource. Derived classes can replace this to implement pack files or asset compression.
		/// </summary>
		/// <param name="assetName">The name of the asset being read.</param>
		protected override Stream OpenStream(string assetName)
		{
			object obj2 = this.resourceManager.GetObject(assetName);
			if (obj2 == null)
			{
				throw new ContentLoadException(String.Format(CultureInfo.CurrentCulture, FrameworkResources.OpenResourceNotFound, new object[] { assetName }));
			}
			byte[] buffer = obj2 as byte[];
			if (buffer == null)
			{
				throw new ContentLoadException(String.Format(CultureInfo.CurrentCulture, FrameworkResources.OpenResourceNotBinary, new object[] { assetName }));
			}
			return new MemoryStream(buffer);
		}
	}
}
